﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using MySQLStudio.BusinessLogic;

namespace MySQLStudio.GUI.Controls
{
    public class ViewScriptWindow : ScriptWindow
    {
        private String m_TableSchema = String.Empty;
        private String m_ViewName = "new_view";
        private String m_CreateViewTemplate = "CREATE VIEW  `{0}`.`{1}` AS";
        private String m_AlterViewTemplate1 = "ALTER ALGORITHM = {0} DEFINER = {1} SQL SECURITY {2} VIEW {3} AS {4}";
        private String m_AlterViewTemplate = "ALTER {0}";

        public String TableSchema
        {
            get { return m_TableSchema; }
            set { m_TableSchema = value; }
        }

        public String ViewName
        {
            get { return m_ViewName; }
            set { m_ViewName = value; }
        }
        public override String SqlStatement
        {
            get { return (m_SqlStatement = ScriptTextBox.Text); }
            set { m_SqlStatement = value; }
        }

        public ViewScriptWindow(Host host, Database database)
            : base(host, database)
        {

        }

        public void LoadNewViewTemplate()
        {
            this.Text = String.Format("{0} on {1}.{2}", m_ViewName,
                                                                          Database != null ? Database.Name : string.Empty,
                                                                          Host != null ? Host.Hostname : string.Empty);
            ScriptTextBox.Text = String.Format(m_CreateViewTemplate, m_TableSchema, m_ViewName);
            ScriptTextBox.OnTextChanged();
        }

        public void LoadAlterView(String schemaName, String viewName)
        {
            m_ViewName = viewName;
            this.Text = String.Format("{0} on {1}.{2}", m_ViewName,
                                                                          Database != null ? Database.Name : string.Empty,
                                                                          Host != null ? Host.Hostname : string.Empty);

            ScriptTextBox.Text = FixAlterViewDBResponse(ViewController.GetAlterViewInDataBase(Host.ConnectionString, schemaName, viewName));
            ScriptTextBox.OnTextChanged();
        }

        private String FixAlterViewDBResponse(String resp)
        {
            int indx = resp.ToLower().IndexOf("create");
            int length = "create".Length;
            return String.Format(m_AlterViewTemplate, resp.Substring(indx + length));
        }
    }
}